package com.ruoyi.system.service.sso;

import com.ruoyi.system.common.Md5Utils;
import com.ruoyi.system.domain.IndsvrSsoApp;
import com.ruoyi.system.domain.IndsvrSsoAppUserMap;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import okhttp3.Cookie;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;

@Component
public class IKUAI implements SimulationLogin{
    @Override
    public Object run(IndsvrSsoApp app, IndsvrSsoAppUserMap user, HttpServletRequest request) throws Exception {


        OkHttpUtils okHttpUtils = new OkHttpUtils();
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("username",user.getUsername());
        stringStringHashMap.put("passwd", Md5Utils.hash(user.getPassword()).toLowerCase());
        byte[] encode = Base64.getEncoder().encode(("salt_11"+user.getPassword()).getBytes(StandardCharsets.UTF_8));
        stringStringHashMap.put("pass", new String(encode));
        stringStringHashMap.put("remember_password", null);
        String url = app.getBaseUrl()+"/Action/login";
        String s = okHttpUtils.postForJson(url,okHttpUtils.getGson().toJson(stringStringHashMap));

        HashMap<String, Cookie> cookie = okHttpUtils.getCookie(new URI(url).getHost());

        String authToken = cookie.get("sess_key").value();


        Auths auths = new Auths();
        auths.token= authToken;
        auths.setUsername(user.getUsername());
        return auths;
    }


    @Data
    public static class Auths{
        String token;
        String login="1";
        String username;

    }

    @Data
    public static class Token{
        private Object data;
        private String expire = null;

    }
}
